package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.util.StrUtil;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.ClassesConfig;
import com.tbit.uqbike.object.pojo.dto.AccountUserWorkConfigDTO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.ClassesConfigService;
import com.tbit.uqbike.webmanager.dao.core.AccountUserDao;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：hzw
 * @date ：Created in 2021/8/24 13:35
 * @description：班次设置接口层
 * @modified By：
 * @version: $
 */
@RestController
@RequestMapping(value = "/classesConfig")
public class ClassesConfigController extends BaseController {
    @Autowired
    private ClassesConfigService classesConfigService;
    @Autowired
    private AccountUserDao accountUserDao;

    /**
     * 增加班次设置
     */
    @RequestMapping(value = "/increaseFrequency")
    @OperateLog(module = ModuleEnum.MAINCLASSESCONFIG, methods = MethodEnum.CLASSESCONFIG_ADD)
    public JsonResult IncreaseFrequency(ClassesConfig classesConfig) {
        Assert.notNull(classesConfig.getAccountId(), "ver.accountId.notNull");
        Assert.notNull(classesConfig.getName(), "ver.name.notNull");
        Assert.notNull(classesConfig.getStartTime(), "ver.startTime.notNull");
        Assert.notNull(classesConfig.getEndTime(), "ver.endTime.notNull");
        checkLength(classesConfig);
        List<ClassesConfig> config = classesConfigService.getClassesConfig(classesConfig);
        if (!config.isEmpty()) {
            throw new BaseException(SystemCodeEnum.CLASSES_CONFIG_EXIST);
        }
        Integer ter = classesConfigService.IncreaseClasses(classesConfig);
        if (ter <= 0) {
            throw new BaseException(SystemCodeEnum.ADD_FAIL);
        }

        return JsonResult.ok();
    }

    /**
     * 班次详情
     */
    @RequestMapping(value = "/queryPage")
    public JsonResult queryPageClasses(@NotNull(message = "ver.accountId.notNull") Integer accountId,
                                       @RequestParam(defaultValue = "1") Integer pageNO,
                                       @RequestParam(defaultValue = "10") Integer rowCount) {

        List<ClassesConfig> list = classesConfigService.getClassesConfigPage(accountId, pageNO, rowCount);

        Integer count = classesConfigService.getClassesConfigCount(accountId);
        return JsonResult.ok(list, count);
    }


    /**
     * 删除班次
     */
    @RequestMapping(value = "/del")
    @OperateLog(module = ModuleEnum.MAINCLASSESCONFIG, methods = MethodEnum.CLASSESCONFIG_DEL)
    public JsonResult delPageClasses(@NotNull(message = "ver.workNumber.notNull") Integer workNumber, HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo == null) {
            throw new BaseException(SystemCodeEnum.LOGIN_EXPIRED);
        }
        Integer ter = classesConfigService.delClasses(workNumber, loginInfo);
        return JsonResult.ok();
    }


    /**
     * 修改班次
     */
    @RequestMapping(value = "/update")
    @OperateLog(module = ModuleEnum.MAINCLASSESCONFIG, methods = MethodEnum.CLASSESCONFIG_UPDATE)
    public JsonResult updatePageClasses(ClassesConfig classesConfig) {
        Assert.notNull(classesConfig.getAccountId(), "ver.accountId.notNull");
        Assert.notNull(classesConfig.getName(), "ver.name.notNull");
        Assert.notNull(classesConfig.getStartTime(), "ver.startTime.notNull");
        Assert.notNull(classesConfig.getEndTime(), "ver.endTime.notNull");
        checkLength(classesConfig);
        List<ClassesConfig> configList = classesConfigService.getClassesConfig(classesConfig);
//        if (!configList.isEmpty()){
//             throw new BaseException(SystemCodeEnum.CLASSES_CONFIG_EXIST);
//        }
        classesConfigService.upClasses(classesConfig);
        return JsonResult.ok();
    }

    /**
     * 班次列表
     */
    @RequestMapping(value = "/classesList")
    public JsonResult classesList(Integer accountId, HttpServletRequest request) {
        Assert.notNull(accountId, "ver.accountId.notNull");
        List<ClassesConfig> list = classesConfigService.getClassesConfig(new ClassesConfig(accountId));

        return JsonResult.ok(list);
    }


    /**
     * 修改工种
     */
    @RequestMapping(value = "/updateWorkType")
    @OperateLog(module = ModuleEnum.MAINCLASSESCONFIG, methods = MethodEnum.CLASSESCONFIG_UPW)
    public JsonResult updateWorkType(Integer accountId, String type, String workNumber, Integer accountUserId) {
        Assert.notNull(accountUserId, "ver.accountUserId.notNull");
        List<String> list = Arrays.asList(type.split(","));
        List<Integer> workNumberList = StringUtil.getIntegerList(workNumber);
        classesConfigService.upWorkType(accountId, list, workNumberList, accountUserId);
        return JsonResult.ok();
    }


    /**
     * 工种详情
     */
    @RequestMapping(value = "/queryPageWorkType")
    public JsonResult queryPage(@NotNull(message = "ver.accountId.notNull") Integer accountId, String type,
                                Integer workNumber, String phone, String regionIds, @RequestParam(defaultValue = "1") Integer pageNO,
                                @RequestParam(defaultValue = "10") Integer rowCount) {
        List<Integer> regionList = StringUtil.getIntegerList(regionIds);
        Integer locationTypes = null;
        //兼容挪车拆分成  前端：2-0 = 超区；2-1 = 站外
        if (StringUtils.isNotEmpty(type) && type.contains("-")){
            String[] split = type.split("-");
            if ("2".equals(split[0]) && "1".equals(split[1])){
                //如果是查询站外工种，type变为15 原因看sql的子查询
                type = "15";
            }else {
                type = split[0];
                locationTypes = Integer.parseInt(split[1]);
            }
        }

        List<AccountUserWorkConfigDTO> list = classesConfigService.queryPage(accountId, type, workNumber, phone, regionList, pageNO, rowCount, locationTypes);
        String typeName = "";
        Set<String> typeNames = new HashSet<>();
        if (!list.isEmpty()) {
            for (AccountUserWorkConfigDTO accountUserWorkConfigDTO : list) {
                List<String> typeList;
                if (accountUserWorkConfigDTO.getType() != null){
                    typeList = Arrays.asList(accountUserWorkConfigDTO.getType().split(","));
                }else {
                    typeList = new ArrayList<>();
                }

                for (String types : typeList) {
                    if ("1".equals(types)) {
                        typeName = "换电";
                    } else if ("2".equals(types)) {
                    typeName = "超区挪车";
                    } else if ("3".equals(types)) {
                        typeName = "维修";
                    }else if ("6".equals(types)){
                        typeName = "调度";
                    }else if ("15".equals(types)){
                        typeName = "站外挪车";
                    }
                    typeNames.add(typeName);
                }
                if (accountUserWorkConfigDTO.getType() != null){
                    accountUserWorkConfigDTO.setType(accountUserWorkConfigDTO.getType().replace("2", "2-0").replace("15", "2-1"));
                }
                String result = typeNames.stream().map(String::valueOf).collect(Collectors.joining(","));
                accountUserWorkConfigDTO.setTypeName(result);
                typeNames.clear();
                if (null == accountUserWorkConfigDTO.getClassesName()) {
                    accountUserWorkConfigDTO.setClassesName("");
                }
            }
        }

        Integer total = classesConfigService.queryCount(accountId, type, workNumber, phone).size();
        return JsonResult.ok(list, total);
    }

    void checkLength(ClassesConfig classesConfig){
        if (StrUtil.isNotEmpty(classesConfig.getName()) && classesConfig.getName().length() > 50){
            throw new BaseException("班次名称过长");
        }
    }

}
